package com.damacheng009.future.alarm.toolkit;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.extra.mail.MailUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HtmlUtil;
import cn.hutool.http.HttpRequest;

public class MailTool {
	// 发往哪个邮箱
	public static final String TO = "marcusxing@163.com";
	
	// slack网页发发消息HTTP接口
	private static final String SLACK_WEBHOOK_URL = "https://hooks.slack.com/services/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";
	
	// slack消息模板
	private static final String SLACK_MSG_PATTERN = "{\"text\":\"%s\"}";

	public static void send(String subject, String content) {
		// 异步发邮件，防止堵塞
		ThreadUtil.excAsync(() -> sendEMail(subject, content), true);
		
		// 异步发slack消息
		ThreadUtil.excAsync(() -> sendSlack(subject + "\n" + content), true);
	}
	
	public static void sendEMail(String subject, String content) {
		MailUtil.send(MailTool.TO, subject, content, true);
	}
	
	public static String sendSlack(String msg) {
		String json = String.format(SLACK_MSG_PATTERN, HtmlUtil.cleanHtmlTag(msg.replace("<br>", "\n")));
		String resp = HttpRequest.post(SLACK_WEBHOOK_URL)
			.header(Header.CONTENT_TYPE, "application/json")
		    .body(json)
		    .execute().body();
		System.out.println("slack resp:" + resp);
		return resp;
	}
}
